package com.jin.flashsaled.config;

import com.jin.flashsaled.entity.User;
import com.jin.flashsaled.utils.CookieUtil;
import io.netty.util.internal.StringUtil;
import jakarta.servlet.http.Cookie;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.MethodParameter;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.support.WebDataBinderFactory;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.method.support.ModelAndViewContainer;

import java.util.Optional;

//用户参数自定义器
//
//
@Component
public class UserArgumentResolver implements HandlerMethodArgumentResolver {

    @Autowired
    RedisTemplate redisTemplate;

    @Override
    public boolean supportsParameter(MethodParameter parameter) {
        //只有这个返回true，下面哪个方法才会执行
        //判断是否是user类型
        Class<?> clazz = parameter.getParameterType();
        return clazz == User.class;
    }

    @Override
    public Object resolveArgument(MethodParameter parameter, ModelAndViewContainer mavContainer, NativeWebRequest webRequest, WebDataBinderFactory binderFactory) throws Exception {
        HttpServletRequest request = webRequest.getNativeRequest(HttpServletRequest.class);
        HttpServletResponse response = webRequest.getNativeResponse(HttpServletResponse.class);
        //从request请求获取cookie
        Optional<String> token = CookieUtil.readCookie(request, "token");
        //判断是否存在cookie
        String cookie= token.orElse("no token");
        if (cookie.equals("no token"))
        {
            return null;
        }
        //根据token从redis获取到user
        User user=(User) redisTemplate.opsForValue().get("user:"+cookie);

        return user;
    }
}
